package cn.samir.sudoku.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ViewSwitcher;
import cn.samir.sudoku.R;
import cn.samir.sudoku.adapter.GameGridViewAdapter;
import cn.samir.sudoku.adapter.SettingsListAdapter;
import cn.samir.sudoku.core.Action;
import cn.samir.sudoku.core.DefaultGames;
import cn.samir.sudoku.core.SettingItem;
import cn.samir.sudoku.core.Sudokus;
import cn.samir.sudoku.db.dao.SudokuDao;
import cn.samir.sudoku.keys.Conf;
import cn.samir.sudoku.net.NetTask;
import cn.samir.sudoku.net.OnNetListener;
import cn.samir.sudoku.util.LogUtils;
import cn.samir.sudoku.util.SharePopWindow;
import cn.samir.sudoku.util.Utils;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;

public class GridMainActivity extends BaseActivity implements
		OnItemClickListener, OnClickListener, TextWatcher {
	private static final String TAGE = "GridMainActivity";
	View parentView;
	GridView mGridView;
	GameGridViewAdapter mGridViewAdapter;
	ArrayList<Sudokus> sudokus;
	ArrayList<Sudokus> searchingShowSudokus = new ArrayList<Sudokus>();
	ArrayList<SettingItem> settingItems = new ArrayList<SettingItem>();
	SettingItem loginItem;
	SettingItem rankItem;
	LinearLayout ll_NormalGroup,ll_SearchGroup;
	ImageView btn_search,iv_changetosearch;
	ImageView iv_share;
	LinearLayout settings_container;
	PopupWindow mSettingsPopupWindow;
	SettingsListAdapter settingsListAdapter;
	ListView popWindowContentView;
	EditText mSearchEditView;
	ViewSwitcher viewSwitcher;
	InputMethodManager imm;
	PullToRefreshGridView mPullRefreshGridView;
	SharePopWindow sharePopWindow;
	ShareParams shareParams;
	Context mContext = this;
	SudokuDao sudokuDao;
	Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				initDatas();
				// mGridViewAdapter.clear();
				// mGridViewAdapter.appendToList(sudokus);
				// loadingDialog.dismiss();
				if (mPullRefreshGridView.isRefreshing()) {
					mPullRefreshGridView.onRefreshComplete();
				}
				break;
			case 6:// 显示的结果
				mGridViewAdapter.clear();
				mGridViewAdapter.appendToList(searchingShowSudokus);
				isHandingTextChange = false;
				break;
			case 10:
				mGridViewAdapter.clear();
				mGridViewAdapter.appendToList(sudokus);
				break;
			case 11:
				Utils.getHistoryFromServer(mContext, handler);
				break;
			case 16:
				initDatas();
				break;
			case 100:

				break;
			default:
				break;
			}
		};
	};

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Action.ORDER_TYPR_CHG)) {
				// 修改排序规则
				sortSudokusArray();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		parentView = View.inflate(this, R.layout.activity_gridmain, null);
		setContentView(parentView);
		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		initViews();
		registerReceiver(broadcastReceiver, new IntentFilter(
				Action.ORDER_TYPR_CHG));
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(broadcastReceiver);
		super.onDestroy();
	}

	private void initViews() {
		// initShareParams();
		
		ll_NormalGroup = getView(R.id.ll_normalpage);
		ll_SearchGroup = getView(R.id.ll_searchEditor);
		sharePopWindow = new SharePopWindow(this);
		sudokuDao = new SudokuDao(this);
		initSettingPopWindow();
		mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.gridview_games);
		mGridView = mPullRefreshGridView.getRefreshableView();
		mPullRefreshGridView
				.setOnRefreshListener(new OnRefreshListener2<GridView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<GridView> refreshView) {
						addMore();
					}

					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<GridView> refreshView) {
						addMore();
					}

				});

		// mGridView = getView(R.id.gridview_games);
		viewSwitcher = getView(R.id.switch_search);
		iv_changetosearch = getView(R.id.iv_changetosearch);
		iv_changetosearch.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				viewSwitcher.showNext();
				mSearchEditView.setVisibility(View.VISIBLE);
				mSearchEditView.requestFocus();
				mSearchEditView.requestFocusFromTouch();
			}
		});
		btn_search = getView(R.id.btn_search);
		btn_search.setOnClickListener(this);
		iv_share = getView(R.id.iv_share);
		iv_share.setOnClickListener(this);
		mSearchEditView = getView(R.id.et_search);
		mSearchEditView.addTextChangedListener(this);
		mSearchEditView.setOnFocusChangeListener(new EditText.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){
					imm.showSoftInput(v, 0);
				}else{
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
					hideEditor(v);
				}
				
			}
		});
		mGridViewAdapter = new GameGridViewAdapter(this);
		// sudokus = getAll();
		// mGridViewAdapter.appendToList(sudokus);
		mGridView.setAdapter(mGridViewAdapter);
		mGridView.setOnItemClickListener(this);

		initDatas();
		checkOtherSettingItem();
	}
	// 隐藏输入发表回帖状态
    private void hideEditor(View v) {
    	imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    	if(viewSwitcher.getDisplayedChild()==1){
    		viewSwitcher.setDisplayedChild(0);
    		mSearchEditView.clearFocus();
    		mSearchEditView.setVisibility(View.GONE);
		}
    }
	private void initsettings() {
		settingItems.clear();
		addRankItem();
		addLoginItem();
		settingItems.add(new SettingItem("分享", R.drawable.share, 21,
				SettingItem.Item_share));
		settingItems.add(new SettingItem("设置", R.drawable.settings, 30,
				SettingItem.Item_Settings));
		settingItems.add(new SettingItem("注销", R.drawable.close, 40,
				SettingItem.Item_LoginOut));
		Collections.sort(settingItems);
		settingsListAdapter.clear();
		settingsListAdapter.appendToList(settingItems);
		
	}
	
	
	@Override
	public void onBackPressed() {
		if(viewSwitcher.getDisplayedChild() == 1){
    		viewSwitcher.setDisplayedChild(0);
    		mSearchEditView.clearFocus();
    		mSearchEditView.setVisibility(View.GONE);
    		handler.sendEmptyMessage(16);
		}else{
			super.onBackPressed();
		}
	}
	private void checkOtherSettingItem() {
		NetTask netTask = new NetTask(mContext);
		netTask.url(Conf.info_url).addRequestCode(10006);
		netTask.doGet(new OnNetListener() {

			@Override
			public void onSuccess(InputStream in) {

			}

			@Override
			public void onSuccess(String result) {

				if (!TextUtils.isEmpty(result)) {
					try {
						JSONObject jsonObject = new JSONObject(result);
						int status = jsonObject.getInt("status");
						if (1 == status) {
							String data = jsonObject.getString("data");
							JSONArray array = new JSONArray(data);
							int count = 0;
							if (array != null) {
								count = array.length();
							}
							for (int i = 0; i < count; i++) {
								JSONObject jsonObject2 = array.getJSONObject(i);
								String key = jsonObject2.getString("key");
								if ("show_rank".equals(key)) {
									int value = jsonObject2.getInt("value");
									Utils.putSharedPre(mContext,
											"showRankItem",
											value != 0 ? "enable" : "disable");
								}
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onError(String result) {

			}
		});

	}

	private void addLoginItem() {
		String showText = "登录";
		if (Utils.getUserName(mContext) != null) {
			showText = Utils.getUserName(mContext);
		}
		loginItem = new SettingItem(showText, R.drawable.login, 10,
				SettingItem.Item_Login);
		settingItems.add(loginItem);
	}

	public void updateSettingPopWindow() {
		if (settingItems != null) {
			Collections.sort(settingItems);
			settingsListAdapter.clear();
			settingsListAdapter.appendToList(settingItems);
			settingsListAdapter.notifyDataSetChanged();
		}
	}

	public void addMore() {
		int size = 0;
		if (sudokus != null) {
			size = sudokus.size();
		} else {
			sudokus = new ArrayList<Sudokus>();
		}
		loadingmoreganme(size);
	}

	// private void initShareParams() {
	// shareParams = new ShareParams();
	// shareParams.text = "分享测试";
	// }

	private void initSettingPopWindow() {

		popWindowContentView = (ListView) View.inflate(this,
				R.layout.pop_listview, null);
		settingsListAdapter = new SettingsListAdapter(this);
		popWindowContentView.setAdapter(settingsListAdapter);
		popWindowContentView.setOnItemClickListener(this);
		mSettingsPopupWindow = new PopupWindow(popWindowContentView);
		mSettingsPopupWindow.setWidth(300);
		mSettingsPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
		mSettingsPopupWindow.setBackgroundDrawable(new ColorDrawable());
		mSettingsPopupWindow.setOutsideTouchable(true);
		mSettingsPopupWindow.setTouchable(true);
		mSettingsPopupWindow.setFocusable(true);
		// initsettings();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	public void addRankItem() {
		if ("enable".equals(Utils.getSharePreString(mContext, "showRankItem"))
				&& !settingItems.contains(rankItem)) {
			rankItem = new SettingItem("排行榜", R.drawable.rank, 20,
					SettingItem.Item_rank);
			settingItems.add(rankItem);
		}
	}

	public void initDatas() {
		// loadingDialog.show("正在初始化..");
		sudokus = sudokuDao.queryAll();
		if (sudokus != null && sudokus.size() > 0) {
			sortSudokusArray();
		} else {
			addMore();
		}

	}

	void sortSudokusArray() {
		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		boolean isOrderByHard = preferences.getBoolean("order_type", false);// false--default
																			// ||
																			// true
																			// ---hard
		Comparator<Sudokus> compartor = null;
		if (!isOrderByHard) {// default
			compartor = new Comparator<Sudokus>() {
				@Override
				public int compare(Sudokus lhs, Sudokus rhs) {

					if (lhs.passed == 1 && rhs.passed == 0) {
						return -1;
					} else if (lhs.passed == 0 && rhs.passed == 1) {
						return 1;
					} else if (lhs.passed == 1 && rhs.passed == 1) {
						return 0;
					} else {// 00
						return lhs.sudokuid > rhs.sudokuid ? 1
								: (lhs.sudokuid == rhs.sudokuid ? 0 : -1);
					}
				}
			};
		} else {// hard
			compartor = new Comparator<Sudokus>() {
				@Override
				public int compare(Sudokus lhs, Sudokus rhs) {
					if (lhs.passed == 1 && rhs.passed == 0) {
						return -1;
					} else if (lhs.passed == 0 && rhs.passed == 1) {
						return 1;
					} else if (lhs.passed == 1 && rhs.passed == 1) {
						return 0;
					} else {// 00
						return lhs.score > rhs.score ? 1
								: (lhs.score == rhs.score ? 0 : -1);
					}

				}
			};
		}
		if (compartor != null) {
			Collections.sort(sudokus, compartor);

		}
		mGridViewAdapter.clear();
		mGridViewAdapter.appendToList(sudokus);

	}

	private void loadingmoreganme(int start_id) {
		OnNetListener onNetListener = new OnNetListener() {

			@Override
			public void onSuccess(InputStream in) {

			}

			@Override
			public void onSuccess(String result) {
				LogUtils.i(TAG, result);
				if (!TextUtils.isEmpty(result)) {

					// JSONObject jsonObject = JSON.parseObject(result);
					int status;
					try {
						org.json.JSONObject jsonObject = new org.json.JSONObject(
								result);
						status = jsonObject.getInt("status");
						System.out.println("status=" + status);
						if (status == 1) {
							String jsonarray = jsonObject.getString("data");
							JSONArray array = new JSONArray(jsonarray);
							System.out.println("data=" + jsonarray);
							int count = 0;
							if (array != null && array.length() > 0) {
								count = array.length();
							}
							for (int i = 0; i < count; i++) {
								String itemstring = array.getString(i);
								JSONObject jo = new JSONObject(itemstring);
								String content = jo.getString("content");
								int score = jo.getInt("score");
								String description = jo
										.getString("description");
								int sudokuid = jo.getInt("sudokuid");
								int id = jo.getInt("id");
								Sudokus s = new Sudokus(id, sudokuid, content,
										description, score);
								// sudokus.add(s);
								sudokuDao.insert(s);
								System.out.println(s.toString());
							}
						}
					} catch (JSONException e) {

						e.printStackTrace();
					}

				}
				handler.sendEmptyMessage(1);
			}

			@Override
			public void onError(String result) {
			}
		};
		NetTask netTask = new NetTask(this);
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("requestcode", "10001");
		param.put("start_id", start_id + "");
		netTask.addParams(param).url(Conf.info_url).doGet(onNetListener);
	}

	public ArrayList<Sudokus> getLocalSudokus() {
		return DefaultGames.games;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		LogUtils.i(TAG, parent.getId() + "," + R.id.lv);
		switch (parent.getId()) {
		default:
			SettingItem item = (SettingItem) settingsListAdapter
					.getItem(position);
			mSettingsPopupWindow.dismiss();
			switch (item.id) {
			case SettingItem.Item_Login:

				if (!Utils.isLogin(mContext)) {
					loginQQ();
				} else {
					Intent intent = new Intent(this, UserHistoryActivity.class);
					startActivity(intent);
				}
				break;
			case SettingItem.Item_rank:
				Intent rankIt = new Intent(this, RankActivity.class);
				startActivity(rankIt);
				break;
			case SettingItem.Item_Settings:
				Intent settingsIt = new Intent(this, SettingsActivity.class);
				startActivity(settingsIt);
				break;
			case SettingItem.Item_share:
				// sharePopWindow.show();
				// new HashMap<String, String>()
				HashMap<String, String> pp = new HashMap<String, String>();
				pp.put("nothing", "usedefault");
				Utils.onekeyshare(this, pp);
				//
				break;
			case SettingItem.Item_LoginOut:
				if (!Utils.isLogin(mContext)) {
					break;
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setIcon(R.drawable.info_warning)
						.setTitle("确认注销账户")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										ShareSDK.initSDK(mContext);
										final Platform plat = ShareSDK
												.getPlatform(QQ.NAME);
										plat.removeAccount(true);
										Utils.loginOut(mContext);

									}
								}).setNegativeButton("取消", null).show();

				break;
			}
			break;
		case R.id.gridview:
			Sudokus sudokus = (Sudokus) mGridViewAdapter.getItem(position);
			LogUtils.i(TAG, sudokus.toString());
			Intent intent = new Intent(this, GameActivity.class);
			intent.putExtra("content", sudokus.content);
			intent.putExtra("sid", sudokus.sid);
			intent.putExtra("description", sudokus.description);
			intent.putExtra("score", sudokus.score);
			intent.putExtra("sudokuid", sudokus.sudokuid);
			startActivity(intent);
			break;

		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_search:
			loadingDialog.show("正在查询");
			NetTask netTask = new NetTask(this);
			HashMap<String, String> param = new HashMap<String, String>();
			String sudokuid = mSearchEditView.getText().toString().trim();
			if (TextUtils.isDigitsOnly(sudokuid)) {
				param.put("sudokuid", mSearchEditView.getText().toString()
						.trim());
				param.put("requestcode", 10005 + "");

			} else {
				LogUtils.showShortToast(mContext, "编号格式有误");
				loadingDialog.dismiss();
				break;
			}
			netTask.url(Conf.info_url).addParams(param)
					.doGet(new OnNetListener() {

						@Override
						public void onSuccess(InputStream in) {

						}

						@Override
						public void onSuccess(String result) {
							LogUtils.i(TAGE, result);
							if (!TextUtils.isEmpty(result)) {
								try {
									JSONObject jsonObject = new JSONObject(
											result);
									int status = jsonObject.getInt("status");
									if (1 == status) {
										String data = jsonObject
												.getString("data");
										JSONObject jo = new JSONObject(data);
										String content = jo
												.getString("content");
										int score = jo.getInt("score");
										String description = jo
												.getString("description");
										int sudokuid = jo.getInt("sudokuid");
										int id = jo.getInt("id");
										Sudokus s = new Sudokus(id, sudokuid,
												content, description, score);
										// sudokus.add(s);
										sudokuDao.insert(s);
										searchingShowSudokus.add(s);
										handler.sendEmptyMessage(6);
									} else {
										LogUtils.showShortToast(mContext,
												"云端题库不存在该id");
									}
								} catch (Exception e) {

								}
							}
							loadingDialog.dismiss();

						}

						@Override
						public void onError(String result) {

						}
					});
			break;
		case R.id.iv_share:
			initsettings();
			if (!mSettingsPopupWindow.isShowing()) {
				mSettingsPopupWindow.showAsDropDown(iv_share);
			} else {
				mSettingsPopupWindow.dismiss();
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 搜索的EditText 监听
	 */
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	/**
	 *
	 */
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// LogUtils.i(TAGE, "s=" + s + ",start=" + start + ",before=" + before
		// + ",count=" + count);

	}

	/**
	 * 目前的s 算法: 总的数据为7 输入>2 的时候，将s转换为int s 为 3位数
	 */
	public boolean isHandingTextChange = false;

	@Override
	public void afterTextChanged(Editable s){
		// LogUtils.i(TAGE, s.toString());
		if (s != null && s.length() > 0) {
			String sedit = s.toString();
			if (!isHandingTextChange) {
				searchingShowSudokus.clear();
				for (Sudokus ss : sudokus) {
					String sudokuid = String.valueOf(ss.sudokuid);
					int length = sedit.length();
					if (sedit.length() > sudokuid.length()) {
						length = sudokuid.length();
					}
					String subString = sudokuid.substring(0, length);
					if (subString.equals(sedit)) {
						searchingShowSudokus.add(ss);
					}
				}
				handler.sendEmptyMessage(6);
			}
		} else {
			handler.sendEmptyMessage(10);
		}
	}
}
